<?php
namespace app\common\model;

use think\Model;

class AuthGroup extends Model
{
    /**
     * 查询一条信息
     *
     * @param array $params
     * @param bool $fields
     * @return array
     */
    public function getInfo(array $params, $fields = true)
    {
        $where = $return = [];

        if (isset($params['id']) && $params['id'] > 0) {
            $where['id'] = $params['id'];
        }

        if (isset($params['title']) && !empty($params['title'])) {
            $where['title'] = $params['title'];
        }

        if (isset($params['code']) && !empty($params['code'])) {
            $where['code'] = $params['code'];
        }

        if (isset($params['status']) && is_numeric($params['status'])) {
            $where['status'] = $params['status'];
        }

        if (!empty($where)) {
            $res = $this->where($where)->field($fields)->find();
            if (!empty($res)) {
                $return = $res->toArray();
            }
        }

        return $return;
    }

    /**
     * @param array $data
     * @return bool|mixed
     */
    public function addData(array $data)
    {
        $res = $this->allowField(true)->data($data,true)->isUpdate(false)->save();
        $return = ($res && isset($this->id) && $this->id > 0) ? $this->id : false;
        // 清空原始数据，防止上一条对下一条的影响
        $this->origin = [];
        return $return;
    }

    /**
     * @param $id
     * @param array $req
     * @return bool | integer
     */
    public function saveDate($id, array $req)
    {
        if ($id <= 0) {
            return false;
        }

        $data = $req;

        $res = $this->allowField(true)->save($data, ['id' => $id]);
        if ($res === false || $res > 1) {
            Log::record('更新资产数据失败：' . $this->getLastSql());
            return false;
        }

        // 清空原始数据，防止上一条对下一条的影响
        $this->origin = [];
        return $res;
    }

    /**
     * 获取所有的角色分组
     */
    public function getAllGroup()
    {
        $return = $this->paginate(100);
        return $return->toArray()['data'];
    }

    /**
     * 通过groupid获取对应的code
     * @param array $ids
     * @return array
     */
    public function getCodeByIds(array $ids)
    {
        $res = $this->where([
            'id' => ['in', $ids]
        ])->field('code')->paginate(100);
        $code = $res->toArray()['data'];
        $code = array_filter(array_unique(array_column($code, 'code')));
        return $code;
    }
}